package feedback

import (
	"context"
	"net/http"
	"time"

	"encoding/json"


	"go.uber.org/zap"

	"internal_training_be/db"
	"internal_training_be/user_mgt"
)

func Run (){
	zap.L().Sugar().Info("---->feedback/feedback.go is run")

	// employeeMiddlewares := user_mgt.EmployeeImpl{}

	adminMiddlewares := user_mgt.AdminImpl{}

	http.Handle("/api/checkEmployeeFeedback",adminMiddlewares.CorsMiddleware(adminMiddlewares.AuthMiddleware(http.HandlerFunc(getEmployeeFeedback))))

	http.Handle("/api/getAllEmployeeFeedbacks",adminMiddlewares.CorsMiddleware(adminMiddlewares.AuthMiddleware(http.HandlerFunc(getAllEmployeeFeedbacks))))
}

func getEmployeeFeedback(w http.ResponseWriter, r *http.Request) {

	zap.L().Sugar().Info("---->feedback/getEmployeeFeedback")

	var msg string

	// 读取请求上下文
	ctx := r.Context()

	// 获取管理员ID
	adminID := ctx.Value("adminId").(string)

	if adminID == "" {
		zap.L().Sugar().Error("获取管理员ID为空")
		return
	}

	var rBody struct {
		EmployeeID string `json:"employee"`
	}

	// 获取请求体中的员工
	err := json.NewDecoder(r.Body).Decode(&rBody)
	if err != nil {
		msg = `解析请求体发生错误,未找到"employee"字段,err: ` + err.Error()
		zap.L().Sugar().Error(msg)
		json.NewEncoder(w).Encode(map[string]interface{}{
			"msg": msg,
			"code": 1,
		})
		return
	}

	employeeID := rBody.EmployeeID

	// 获取数据库连接
	dbConn, err := db.GetDBConn()
	if err != nil {
		zap.L().Sugar().Errorf("获取数据库连接失败, err: %v", err.Error())
		return
	}

	if dbConn == nil {
		zap.L().Sugar().Error("获取数据库连接失败, dbConn为空")
		return
	}

	defer dbConn.Release()

	var feedbackData []map[string]interface{}

	rows, err := dbConn.Query(context.Background(), `SELECT * FROM s_training_system.t_feedback WHERE employee_id = $1`, employeeID)
	if err != nil {
		msg = "查询反馈表中的反馈数据失败, err: " + err.Error()
		zap.L().Sugar().Error(msg)
		json.NewEncoder(w).Encode(map[string]interface{}{
			"msg": msg,
			"code": 1,
		})
		return
	}

	for rows.Next() {
		var feedbackID string
		var employeeID string
		var employeeName string
		var content string
		var courseID string
		var courseName string
		var createTime time.Time
		var feedbackStatus int
		var mark int

		err := rows.Scan(&feedbackID, &employeeID, &courseID, &content, &createTime, &feedbackStatus, &mark)
		if err != nil {
			msg = "扫描反馈表中的反馈数据失败, err: " + err.Error()
			zap.L().Sugar().Error(msg)
			json.NewEncoder(w).Encode(map[string]interface{}{
				"msg": msg,
				"code": 1,
			})
			return
		}

		// 获取数据库连接
		dbConn, err := db.GetDBConn()
		if err != nil {
			zap.L().Sugar().Errorf("获取数据库连接失败, err: %v", err.Error())
			return
		}

		if dbConn == nil {
			zap.L().Sugar().Error("获取数据库连接失败, dbConn为空")
			return
		}

		defer dbConn.Release()

		// 获取员工姓名
		err = dbConn.QueryRow(context.Background(), `SELECT username FROM s_training_system.t_employee WHERE id = $1`, employeeID).Scan(&employeeName)
		if err != nil {
			msg = "查询员工姓名失败, err: " + err.Error()
			zap.L().Sugar().Error(msg)
			continue
		}

		// 获取课程名称
		err = dbConn.QueryRow(context.Background(), `SELECT name FROM s_training_system.t_course WHERE id = $1`, courseID).Scan(&courseName)
		if err != nil {
			msg = "查询课程名称失败, err: " + err.Error()
			zap.L().Sugar().Error(msg)
			continue
		}

		feedbackMap := map[string]interface{}{
			"feedbackID": feedbackID,
			"employeeID": employeeID,
			"employeeName": employeeName,
			"content": content,
			"courseID": courseID,
			"courseName": courseName,
			"createTime": createTime,
			"feedbackStatus": feedbackStatus,
			"mark": mark,
		}

		feedbackData = append(feedbackData, feedbackMap)

	}


	json.NewEncoder(w).Encode(map[string]interface{}{
		"msg": "查询反馈表中的反馈数据成功",
		"code": 0,
		"data": feedbackData,
	})

}

func getAllEmployeeFeedbacks(w http.ResponseWriter, r *http.Request) {

	zap.L().Sugar().Info("---->feedback/getAllEmployeeFeedbacks")

	var msg string

	// 读取请求上下文
	ctx := r.Context()

	// 获取管理员ID
	adminID := ctx.Value("adminId").(string)

	if adminID == "" {
		zap.L().Sugar().Error("获取管理员ID为空")
		return
	}

	// 获取数据库连接
	dbConn, err := db.GetDBConn()
	if err != nil {
		zap.L().Sugar().Errorf("获取数据库连接失败, err: %v", err.Error())
		return
	}

	if dbConn == nil {
		zap.L().Sugar().Error("获取数据库连接失败, dbConn为空")
		return
	}

	defer dbConn.Release()

	rows, err := dbConn.Query(context.Background(), `SELECT * FROM s_training_system.t_feedback`)
	if err != nil {
		msg = "查询反馈表中的反馈数据失败, err: " + err.Error()
		zap.L().Sugar().Error(msg)
		json.NewEncoder(w).Encode(map[string]interface{}{
			"msg": msg,
			"code": 1,
		})
		return
	}

	var feedbacks []map[string]interface{}

	for rows.Next() {
		var feedbackID string
		var employeeID string
		var employeeName string
		var content string
		var courseID string
		var courseName string
		var createTime time.Time
		var feedbackStatus int
		var mark int

		err := rows.Scan(&feedbackID, &employeeID, &courseID,&content, &createTime, &feedbackStatus, &mark)
		if err != nil {
			msg = "扫描反馈表中的反馈数据失败, err: " + err.Error()
			zap.L().Sugar().Error(msg)
			json.NewEncoder(w).Encode(map[string]interface{}{
				"msg": msg,
				"code": 1,
			})
			return
		}

		// 获取数据库连接
		dbConn, err := db.GetDBConn()
		if err != nil {
			zap.L().Sugar().Errorf("获取数据库连接失败, err: %v", err.Error())
			return
		}

		if dbConn == nil {
			zap.L().Sugar().Error("获取数据库连接失败, dbConn为空")
			return
		}

		defer dbConn.Release()

		// 获取员工姓名
		err = dbConn.QueryRow(context.Background(), `SELECT username FROM s_training_system.t_employee WHERE id = $1`, employeeID).Scan(&employeeName)
		if err != nil {
			msg = "查询员工姓名失败, err: " + err.Error()
			zap.L().Sugar().Error(msg)
			continue
		}

		// 获取课程名称
		err = dbConn.QueryRow(context.Background(), `SELECT name FROM s_training_system.t_course WHERE id = $1`, courseID).Scan(&courseName)
		if err != nil {
			msg = "查询课程名称失败, err: " + err.Error()
			zap.L().Sugar().Error(msg)
			continue
		}

		feedbackMap := map[string]interface{}{
			"feedbackID": feedbackID,
			"employeeID": employeeID,
			"employeeName": employeeName,
			"content": content,
			"courseID": courseID,
			"courseName": courseName,
			"createTime": createTime,
			"feedbackStatus": feedbackStatus,
			"mark": mark,
		}

		feedbacks = append(feedbacks, feedbackMap)
	}

	json.NewEncoder(w).Encode(map[string]interface{}{
		"msg": "查询反馈表中的反馈数据成功",
		"code": 0,
		"data": feedbacks,
	})

}